<template>
    <div>
        <Modal v-model="modal1"
        :title="title"
        @on-ok="ok"
        width=700
        :mask-closable=false
        @on-visible-change="change"
        @on-cancel="cancel">
            <Form :label-width="80" ref="formValidate" :model="formValidate" :rules="ruleValidate" :show-message="false" style="overflow:hidden" inline>
                <FormItem :label-width="100" label="员工姓名:" prop="name" style="width:100%;margin-bottom:10px;">
                    <Input v-model="formValidate.name" :disabled="isDisabled" placeholder="请输入姓名"></Input>
                </FormItem>

                <FormItem :label-width="100" label="员工电话:" prop="tel" style="width:100%;margin-bottom:10px;">
                    <Input v-model="formValidate.tel" :disabled="isDisabled || !!roleId" placeholder="请输入电话"></Input>
                    <span v-if="!isDisabled && !!roleId" style="font-size:12px;">如需更改手机号码，请删除后重新添加</span>
                </FormItem>

                <FormItem :label-width="100" label="员工角色:" prop="role" style="width:100%;margin-bottom:10px;">
                    <Select  v-model="formValidate.role" @on-change="getRoleById" :disabled="isDisabled" placeholder="请选择角色">
                        <Option
                        v-for="item in roles"
                        v-if="item.id!=100"
                        :value="item.id"
                        :class="{'classic-role':item.id<200 }"
                        :key="item.id">{{item.id < 200? item.name+'(经典角色)' : item.name }}</Option>
                    </Select>
                    <div style="font-size:12px" v-if="formValidate.role">{{home_appointed?'管理门店指定房源':'管理门店所有房源'}}</div>
                </FormItem>

                <FormItem :label-width="100" label="所属门店:" prop="branchesId" style="width:100%;margin-bottom:16px;">
                    <Select multiple v-model="formValidate.branchesId" :disabled="isDisabled" placeholder="默认为总部">
                        <Option v-for="item in branches" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem>

                <div class="staff-permission">
                    <Spin v-if="loadingPermission" fix></Spin>
                    <div class="staff-permission__container">
                        <div v-for="category in permissionList" :key="category.id" class="staff-permission__row">
                            <div class="staff-permission__title">{{category.name}}</div>

                            <CheckboxGroup v-model="rolePermissionIds">
                                <div class="staff-permission__list" v-for="group in category.groups" :key="group.id">
                                    <div class="staff-permission__list__title">
                                        {{group.name}}
                                    </div>
                                    <div class="staff-permission__list__row">
                                        <Checkbox
                                            disabled
                                            class="staff-permission__list__item"
                                            :key="permission.id"
                                            :label="permission.id"
                                            v-for="permission in group.permissions">
                                            {{permission.name}}
                                        </Checkbox>
                                    </div>
                                </div>
                            </CheckboxGroup>
                        </div>
                    </div>
                </div>
            </Form>
            <div slot='footer'>
                <Button type='ghost' v-show="!isDisabled" @click='modal1 = false'>取消</Button>
                <Button type='primary' v-show="!isDisabled" :loading="isLoading" @click="ok('formValidate')">保存</Button>

                <Button type='ghost' v-show="isDisabled" @click='modal1 = false'>关闭</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
// import util from '@/libs/util';
import validate from '@/libs/validate'
import { http, api } from '@/libs/http'
import dataCenter from '@/libs/dataCenter'

export default {
  props: {
    modal: {
      default: false
    },
    roles: {
      default: []
    },
    roleId: {
      default: ''
    },
    userInfoReadonly: {
      default: false
    }
  },
  data () {
    return {
      loadingPermission: false,
      isLoading: false,
      formValidate: {
        name: '',
        tel: '',
        branchesId: [],
        role: ''
      },
      array: [],
      value: '',
      model10: '',
      branches: [],
      permissionList: [],
      rolePermissionIds: [],
      title: '',
      home_appointed: null, // 是否管理门店指定房源
      ruleValidate: {
        name: [{ required: true, message: '请输入名字', trigger: 'blur' }],
        tel: [{ required: true, message: '请输入电话', trigger: 'blur' }, { validator: validate.validPhone, trigger: 'blur' }],
        branchesId: [
          {
            required: false,
            type: 'array',
            message: '请选择门店',
            trigger: 'change'
          }
        ],
        role: [
          {
            required: true,
            type: 'number',
            message: '请选择角色',
            trigger: 'change'
          }
        ]
      }
    }
  },
  computed: {
    modal1: {
      get: function () {
        return this.modal
      },
      set: function (v) {
        this.$emit('update', v)
      }
    },
    isDisabled () {
      return !!this.userInfoReadonly
    },
    userHasBranch () {
      // 判断用户是否有所属门店
      const userBranchs = this.$store.state.user.branches
      return !!userBranchs.length
    }
  },

  methods: {
    ok (name) {
      if (!this.checkUserName()) return
      this.$refs[name].validate(valid => {
        if (!valid) return
        if (this.roleId) {
          this.roleId.role_id === 104 ? this.handleEditKeeper() : this.editStaff()
        } else {
          this.addStaff()
        }
      })
    },
    checkUserName () {
      const { name } = this.formValidate
      if (!validate.regexEnum.legalName.reg.test(name)) {
        this.$Message.error('姓名请使用15位以内的中英文或数字或-组合的字符')
        return false
      }
      return true
    },
    handleEditKeeper () {
      this.$Modal.confirm({
        title: '提示',
        content: '信息更新后，管理房源可能发生变更，请确认。',
        onOk: () => {
          this.editStaff()
        }
      })
    },
    // 获取所有权限
    getActions () {
      dataCenter.getPermissions(this, res => {
        this.permissionList = res
      })
    },
    // 打开页面
    change (val) {
      this.$refs['formValidate'].resetFields()
      if (val) {
        this.getBrances()
        this.getActions()
      }
      if (val && this.roleId) {
        // let selectedRole = this.roles.filter(item => {
        //     return item.id == this.roleId.role_id;
        // });

        this.formValidate.name = this.roleId.name
        this.formValidate.tel = this.roleId.telephone
        this.formValidate.role = this.roleId.role_id

        this.roleId.branches.forEach(item => {
          this.formValidate.branchesId.push(item.id)
        })
        this.title = '编辑员工'
        this.getRoleById(this.roleId.role_id)
      } else {
        this.formValidate.name = ''
        this.formValidate.tel = ''
        this.formValidate.role = ''
        this.formValidate.branchesId = []
        this.rolePermissionIds = []
        this.title = '添加员工'
      }
    },
    // 获取角色
    getRoles () {
      let _this = this
      http.request(this, api.role_list, null, null, (res, err) => {
        if (err || !res) {
          return
        }
        _this.roles = res.rows.sort((a, b) => {
          return a.id - b.id
        })
      })
    },
    // 获取门店
    getBrances () {
      dataCenter.getStores(this, (res, err) => {
        if (err || !res) {
          return
        }
        this.branches = res
      })
    },
    // 添加员工
    addStaff () {
      const params = {
        role_id: this.formValidate.role,
        name: this.formValidate.name,
        telephone: this.formValidate.tel,
        description: this.formValidate.name,
        country_code: '86',
        branch_id: this.formValidate.branchesId
      }

      if (this.formValidate.branchesId.length === 0 && this.userHasBranch) {
        this.$Message.error('请选择门店。')
        return
      }

      this.isLoading = true
      http.request(this, api.user_create, null, params, (res, err) => {
        this.isLoading = false
        if (err || !res) {
          return
        }
        this.$Message.success('添加员工成功')
        this.modal1 = false
        // console.log(res);
        this.$emit('updateList')
      })
    },
    // 获取用户信息
    staffInfo () {
      if (this.roleId) {
        let id = this.roleId.id
        http.request(this, api.user_info_by_id, [id], null, (res, err) => {
          if (err || !res) {
            return
          }
          this.formValidate.name = res.name
          this.formValidate.tel = res.telephone
          this.formValidate.role = res.role_id
        })
      }
    },
    // 编辑用户信息
    editStaff () {
      let id = this.roleId.id
      let obj = {
        role_id: this.formValidate.role,
        name: this.formValidate.name,
        telephone: this.formValidate.tel,
        description: this.formValidate.name,
        country_code: '86',
        branch_id: this.formValidate.branchesId
      }
      this.isLoading = true
      http.request(this, api.user_update, [id], obj, (res, err) => {
        this.isLoading = false
        if (err || !res) {
          return
        }
        this.$Message.success('修改成功')
        this.modal1 = false
        this.$emit('updateList')
      })
    },
    cancel () {},

    getRoleById (roleId) {
      if (!roleId) {
        return
      }
      this.loadingPermission = true
      http.request(this, api.role_info, [roleId], null, (res, err) => {
        this.loadingPermission = false
        if (res) {
          this.home_appointed = res.home_appointed
          this.rolePermissionIds = res.permission_groups.reduce((result, category) => {
            return result.concat(category.permissions.map(p => p.id))
          }, [])
        }
      })
    }
  }
}
</script>

<style lang="less">
@import '../staff.less';

.classic-role {
    font-weight: bold;
}
.role-wrapper {
    background-color: #f3f3f3;
    border-radius: 4px;
    padding: 5px 15px 5px 15px;
    max-height: 320px;
    overflow: auto;

    .role-item {
        padding-bottom: 8px;
        border-bottom: 1px solid #dddee1;
    }
    .role-item:last-child {
        padding-bottom: 8px;
        border-bottom: none;
    }
}
</style>
